package com.qingcloud.base.response;

import com.qingcloud.base.pojo.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;


/**
 * 返回数据统一包装策略
 *
 * @author wangjinnan
 */
public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {

    public static final Logger logger = LoggerFactory.getLogger(ResponseBodyWrapHandler.class);

    private final HandlerMethodReturnValueHandler delegate;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return delegate.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        //判断是否需要包装
        if (returnValue instanceof com.qingcloud.base.pojo.ApiResult || returnValue instanceof SseEmitter) {
            //ignore 业务已经返回统一对象
        } else {
            //包装统一返回对象
            returnValue = ApiResult.success(returnValue);
        }
        delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    }
}
